// pages/register/register.js
import request from '../../utils/request.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickname: '',
    phone: '',
    password: '',
    captcha: '', //验证码
    userInfo: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  handleSendcode() {
    let {
      nickname,
      phone,
      password,
    } = this.data
    if (!phone || !nickname || !password) {
      wx.showToast({
        title: '信息不能为空',
        icon: 'none'
      })
      return;
    }
    this.getSendInfoList(phone);
  },
  handleLogin(event) {
    let type = event.currentTarget.dataset.type;
    this.setData({
      [type]: event.detail.value
    })
  },
  toLogin() {
    wx.reLaunch({
      url: '/pages/login/login'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  async getUserInfo() {
    let {
      nickname,
      phone,
      password,
      captcha
    } = this.data
    let result = await request('/register/cellphone', {
      phone,
      password,
      captcha,
      nickname
    });
    if (result.code === 200) {
      wx.setStorageSync('userInfo', JSON.stringify(result.profile));
      wx.showToast({
        title: '登录成功'
      });
      wx.reLaunch({
        url: '/pages/personal/personal',
      });
    } else if (result.code === 503) {
      wx.showToast({
        title: '验证码错误',
        icon: 'none'
      })
    } else {
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      })
    }
  },
  async register() {
    let {
      nickname,
      phone,
      password,
      captcha
    } = this.data
    if (!phone || !nickname || !password || !captcha) {
      wx.showToast({
        title: '信息不能为空',
        icon: 'none'
      })
      return;
    }
    if (!nickname.includes('-') || !nickname.includes('_')){
      wx.showToast({
        title: '昵称只支持中英文、数字和-_两个符号',
        icon: 'none'
      })
    }

    //检查手机格式是否符合规范
    let phoneData = /^1[3-9]\d{9}$/;
    if (!phoneData.test(phone)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'none'
      })
      return;
    }

    //检测验证码是否正确
    let result = await request('/captcha/verify', {
      phone,
      captcha
    })
    if (result.data == true) {
      this.getUserInfo();
    }
  },

  async getSendInfoList(phone) {
    let result = await request('/captcha/sent', {
      phone
    })
    if (!result.data) {
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})